package com.sdy.resdir.web.controller.deptadmin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.auth.api.AuthApi;
import com.sdy.auth.api.model.AuthDto;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DesensitizeUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.service.FileService;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.param.IpApprovalParam;
import com.sdy.resdir.biz.service.*;
import com.sdy.resdir.biz.util.CopyUtil;
import com.sdy.resdir.biz.util.DeCodeUtil;
import com.sdy.resdir.biz.vo.IpApplyInfoVo;
import com.sdy.resdir.biz.vo.IpApplyListVo;
import com.sdy.resdir.biz.vo.UserInfoVo;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.UserDTO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 机构管理员接口类
 *
 * @author hyh
 * @since 2019-10-24
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/deptAdmin")
@Api(tags = "机构管理员接口Api")
public class DeptAdminController {
    @Autowired
    private RdSelfBuiltSystemService appService;
    @Autowired
    private RdSystemIpService appIpService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private RdImplementationOrderService implementationOrderService;
    @Autowired
    private RdResManagementService resManagementService;
    @Autowired
    private RdIpUpdateApplicationService ipUpdateApplyService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Autowired
    private RdResDetailsApiService rdResDetailsApiService;
    @Autowired
    private RdResDataItemService rdResDataItemService;
    @Autowired
    private RdResourceDirDataService rdResourceDirDataService;
    @Autowired
    private AuthApi authApi;
    @Autowired
    private FileService fileService;
    @Value("${res.app.code}")
    private String appCode;

    // ---------------------------------------------------登    录-------------------------------------------------------

    @ApiOperation(value = "用户获取个人信息", response = UserInfoVo.class)
    @GetMapping("/userInfo")
    public Response userInfo(HttpServletRequest request) throws BizException {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        UserDTO user = userQueryApi.getUser(userId);
        AuthDto authTree = authApi.getAuthTree(appCode, userId);
        String fsUploadAddr = fileService.getFsUploadAddr();
        user.setIdCard(DesensitizeUtil.hideIdCardNo(user.getIdCard()))
                .setPhone(DesensitizeUtil.hideCellPhone(user.getPhone()));
        UserInfoVo userinfo = CopyUtil.clone(user, UserInfoVo.class);
        userinfo.setOwnDeptName(user.getOwnDeptName());
        userinfo.setOwnDeptId(user.getOwnDeptId());
        userinfo.setRoleDtos(userQueryApi.listRoleByIds(user.getRoleIdList()));

        Map<String, Boolean> map = authTree.convertToMap();
        List<String> removeKeys = new ArrayList<>();
        for (Map.Entry<String, Boolean> entry : map.entrySet()) {
            if (entry.getValue() == false) {
                removeKeys.add(entry.getKey());
            }
        }
        removeKeys.forEach(key -> {
            map.remove(key);
        });

        userinfo.setAuthTree(map);
        userinfo.setUploadUrl(fsUploadAddr);
        return Response.success(userinfo);
    }


    // ---------------------------------------------------自建系统-------------------------------------------------------

    @ApiOperation(value = "查询自建系统列表", response = RdSelfBuiltSystem.class)
    @GetMapping("/getAppList")
    public Response getAppList(HttpServletRequest request) {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        UserDTO user = userQueryApi.getUser(userId);
        List<RdSelfBuiltSystem> appList = appService.list(Wrappers.<RdSelfBuiltSystem>lambdaQuery()
                .eq(RdSelfBuiltSystem::getSysState, 0)
                .eq(RdSelfBuiltSystem::getDeptId, user.getOwnDeptId())
        );
        if (appList.isEmpty()) {
            return Response.success(appList);
        }
        List<Integer> appIdList = appList.stream().map(RdSelfBuiltSystem::getId).collect(Collectors.toList());
        List<RdSystemIp> ipList = appIpService.list(Wrappers.<RdSystemIp>lambdaQuery().in(RdSystemIp::getRelfSysId, appIdList));
        for (RdSelfBuiltSystem app : appList) {
            for (RdSystemIp ip : ipList) {
                if (app.getId().equals(ip.getRelfSysId())) {
                    app.getIpList().add(new RdSystemIp().setIp(ip.getIp()).setId(ip.getId()));
                }
            }
        }
        return Response.success(appList);
    }

    @ApiOperation(value = "根据自建系统ID查询详情", response = RdSelfBuiltSystem.class)
    @GetMapping("/getAppInfoById")
    public Response getAppInfoById(Integer id) throws BizException {
        RdSelfBuiltSystem appInfo = appService.getAppInfo(id);
        return Response.success(appInfo);
    }


    @ApiOperation(value = "新增自建系统")
    @PostMapping("/createApp")
    public Response createApp(@RequestBody @ApiParam(name = "app") RdSelfBuiltSystem app, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户未登录");
        int createState = appService.createApp(app, userInfo.getUserId());
        return createState == 1 ? Response.success() : Response.error();
    }

    @ApiOperation(value = "修改自建系统")
    @PostMapping("/updateApp")
    public Response updateApp(@RequestBody @ApiParam(name = "app") RdSelfBuiltSystem app, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户未登录");
        appService.updateApp(app, userInfo.getUserId());
        return Response.success();
    }

    @ApiOperation(value = "删除自建系统")
    @PostMapping("/delAppById")
    public Response delAppById(@RequestBody @ApiParam(name = "id") Map<String, Object> map) throws BizException {
        Integer id = (Integer) map.get("id");
        Assert.isNull(id, "id不可为空");
        boolean app = appService.removeById(id);
        boolean appIp = appIpService.remove(Wrappers.<RdSystemIp>lambdaUpdate().eq(RdSystemIp::getRelfSysId, id));
        return app && appIp ? Response.success() : Response.error();
    }


    // ---------------------------------------------------审   批-------------------------------------------------------


    // --------------------------------------------------IP修改申请------------------------------------------------------

    @ApiOperation(value = "IP修改申请单-申请列表", response = IpApplyListVo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appName", value = "自建系统名称"),
            @ApiImplicitParam(name = "ip", value = "ip地址"),
            @ApiImplicitParam(name = "state", value = "资源名称:模糊查询")
    }
    )
    @GetMapping("/ipOrderManagerList")
    public Response ipOrderManagerList(Page page, String appName, String ip, Integer state, HttpServletRequest request) throws BizException, UnsupportedEncodingException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户还未登录");
        appName = DeCodeUtil.decodeParam(appName);
        IPage<IpApplyListVo> managerIpOrderList = ipUpdateApplyService.getUserIpOrderList(page, appName, ip, state, userInfo.getUserId());
        return Response.success(managerIpOrderList);
    }


    @ApiOperation(value = "IP修改申请单-查看订单详情", response = IpApplyInfoVo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单Id"),
    }
    )
    @GetMapping("/getIpApplyInfo")
    public Response getIpApplyInfo(Integer id, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户还未登录");
        IpApplyInfoVo ipApplyInfo = ipUpdateApplyService.getIpApplyInfo(userInfo.getUserId(), id);
        return Response.success(ipApplyInfo);
    }

    @ApiOperation(value = "IP修改申请单-审批接口")
    @PostMapping("/ipOrderApproval")
    public Response ipOrderApproval(@RequestBody @ApiParam("param") IpApprovalParam param, HttpServletRequest request) throws Exception {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户还未登录");
        ipUpdateApplyService.ipOrderApproval(userInfo.getUserId(), param.getResult(), param.getRemark(), param.getIpApplyNo());
        return Response.success();
    }


    // ---------------------------------------------------资源申请-------------------------------------------------------


    // ---------------------------------------------------资源管理-------------------------------------------------------

    @ApiOperation(value = "我的资源页面-服务/交换/页面", response = RdImplementationOrder.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "implementationState", value = "实施状态 1实施完成 3已回收 4资源待回收)"),
            @ApiImplicitParam(name = "resType", value = "1.服务接口类 2.服务页面类 3.数据交换"),
            @ApiImplicitParam(name = "resName", value = "模糊查询搜索内容")
    })
    @GetMapping("/getMyUserList")
    public Response getMyUserList(Page page, Integer implementationState, Integer resType, String resName, HttpServletRequest request) throws Exception {
        resName = DeCodeUtil.decodeParam(resName);
        UserInfo userInfo = ssoService.getUserInfo(request);
        UserDTO user = userQueryApi.getUser(userInfo.getUserId());
        Assert.isNull(userInfo, "用户未登录");
        Integer userId = userInfo.getUserId();
        List<RdResManagement> userResList = resManagementService.list(Wrappers.<RdResManagement>lambdaQuery()
                .eq(RdResManagement::getDeptId, user.getOwnDeptId()));
        // 如果查询不到用户拥有资源,则直接返回空列表
        if (userResList.isEmpty()) {
            List<RdImplementationOrder> list = new ArrayList<>();
            return Response.success(list);
        }
        IPage pageData = implementationOrderService.page(page, Wrappers.<RdImplementationOrder>lambdaQuery()
                .eq(null != implementationState, RdImplementationOrder::getImplementationState, implementationState)
                .eq(null != resType, RdImplementationOrder::getResType, resType)
                .eq(RdImplementationOrder::getOrderType, 1)
                .like(StringUtil.isNotBlank(resName) && StringUtil.isNotEmpty(resName), RdImplementationOrder::getResName, resName)
                .in(!userResList.isEmpty(), RdImplementationOrder::getUserId, userResList.stream().map(RdResManagement::getUserId).collect(Collectors.toList()))
                .in(null == implementationState, RdImplementationOrder::getImplementationState, 1, 3, 4)
                .orderByAsc(RdImplementationOrder::getImplementationState)
        );
        return Response.success(pageData);
    }

    @ApiOperation(value = "我的资源页面-资源详情")
    @ApiImplicitParam(name = "resId", value = "资源id")
    @GetMapping("/myRedDetail")
    public Response myResDetail(Integer resId) throws BizException {
        Assert.isNull(resId, "无法获取资源信息，请联系管理员");
        RdResourceDir rdResourceDir = rdResourceDirService.getById(resId);
        Assert.isNull(rdResourceDir, "无法获取资源信息，请联系管理员");
        Map<String, Object> detail = new HashMap(16);
        if (rdResourceDir.getResType() != null && rdResourceDir.getResType() == 1) {
            RdResDetailsApi one = rdResDetailsApiService.getOne(new LambdaQueryWrapper<RdResDetailsApi>().eq(RdResDetailsApi::getResDirId, resId));
            detail.put("detail", one);
        } else if (rdResourceDir.getResType() != null && rdResourceDir.getResType() == 2) {
            RdResourceDirData one = rdResourceDirDataService.getOne(new LambdaQueryWrapper<RdResourceDirData>().eq(RdResourceDirData::getResDirId, resId));
            detail.put("detail", one);
        } else if (rdResourceDir.getResType() != null && rdResourceDir.getResType() == 3) {
            RdResDataItem one = rdResDataItemService.getOne(new LambdaQueryWrapper<RdResDataItem>().eq(RdResDataItem::getOwnResId, resId));
            detail.put("detail", one);
        }
        return Response.success(detail);
    }


    @ApiOperation(value = "资源管理-分页查询资源-普通部门使用", response = RdResourceDir.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "state", value = "资源状态: 0-已发布 1-未发布"),
            @ApiImplicitParam(name = "type", value = "资源类型: (1.服务接口类 2.服务页面类 3.数据教换类)"),
            @ApiImplicitParam(name = "resName", value = "资源名称:模糊查询")
    }
    )
    @GetMapping("/deptResPageList")
    public Response deptResPageList(Page page, Integer state, Integer type, String resName, HttpServletRequest request) throws UnsupportedEncodingException {
        resName = DeCodeUtil.decodeParam(resName);
        Integer userId = ssoService.getUserId(request);
        UserDTO user = userQueryApi.getUser(userId);
        IPage<RdResourceDir> data = rdResourceDirService.deptResPageList(page, state, type, resName, user.getOwnDeptId());
        return Response.success(data);
    }

}
